'''
Created on 18.11.2009



@author: guest
'''
from ru.simpleprojecttool.utils.utils import canEditProject
from ru.simpleprojecttool.comment import Comment

import os
from google.appengine.ext.webapp import template
from ru.simpleprojecttool.db.model import Project, ParticipantRole, Role, Task
from ru.simpleprojecttool.db.model import Participant
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from ru.simpleprojecttool.role import role
from ru.simpleprojecttool.user import user
from ru.simpleprojecttool.task import task
from ru.simpleprojecttool.utils import utils

class ProjectWithSettings(object):
    project = Project
    canEdit = bool
    def __init__(self, project, canEdit):
        self.project = project
        self.canEdit = canEdit

class ListProject(webapp.RequestHandler):
    def get(self):
        if not users.get_current_user(): 
            self.redirect('/')
        
        myProjects = []
        currentUser = users.get_current_user()
        participants = Participant.all().filter("user = ", currentUser)
        
        for participant in participants:
            if not myProjects.__contains__(participant.project):
                myProjects.append(ProjectWithSettings(project = participant.project, canEdit = False))#utils.participantCanEditProject(participant)))
        
        template_values = {
            'projects': myProjects,
        }
        
        utils.showTemplate(self, '../../../templates/project/projects.html', [], template_values)

class CreateProject(webapp.RequestHandler):
    def get(self):
        if not users.get_current_user(): 
            self.redirect('/')
        template_values = {}
        
        utils.showTemplate(self, '../../../templates/project/createProject.html', [], template_values)

class CreateNewProject(webapp.RequestHandler):
    def post(self):
        if not users.get_current_user(): 
            self.redirect('/')
        projectName = self.request.get('projectName') 
        description = self.request.get('description') 
        
        project = Project(name = projectName, 
                          description = description, 
                          creator = users.get_current_user())
        
        project.put() ;

        participant = Participant(user = users.get_current_user(), 
                                  project = project) ;
        participant.put()
        
        adminRole = Role(name = "Project admin", canEditProject = True, project = project)
        adminRole.put()
        
        pRole = ParticipantRole(participant = participant, role = adminRole)
        pRole.put()
        
        self.redirect('/projects')

class Login(webapp.RequestHandler):
    def get(self):
        if users.get_current_user():
            self.redirect('/projects')
        else:
            self.redirect(users.create_login_url(self.request.uri)) 
            
class Logout(webapp.RequestHandler):
    def get(self):
        if users.get_current_user():
            self.redirect(users.create_logout_url('/')) 
            
class EditProjectForm(webapp.RequestHandler):
    project = Project
    def execute(self):
        template_values = {
                  'project': self.project
        }
        utils.showTemplate(self, '../../../templates/project/editProject.html', [], template_values)
    def get(self):
        self.project = db.get(db.Key(self.request.get('projectId')))
        utils.checkProject(self.project, self)
        
#       if utils.canEditProject(project):
#          template_values = {
#                   'project': project
#        }
#       utils.showTemplate(self, '../../../templates/project/editProject.html', [], template_values)
#  else:
#     utils.showTemplate(self, '../../../templates/error.html', [utils.Error(message = 'You can\'t acces this page', level = 'error')], {})
              

            
class EditProject(webapp.RequestHandler):
    def post(self):
        project = db.get(db.Key(self.request.get('projectId')))
        if utils.canEditProject(project) == False:
            utils.showTemplate(self, '../../../templates/error.html', [utils.Error(message = 'You can\'t acces this page', level = 'error')], {})
            return
        project.name = self.request.get('projectName') 
        project.description = self.request.get('description') 
        project.put()
        self.redirect('/projects')
        
class DeleteProject(webapp.RequestHandler):
    def post(self):
        project = db.get(db.Key(self.request.get('projectId')))
        if utils.canEditProject(project):
            
            participants = Participant.all().filter('project = ', project)
            for participant in participants:
                pRoles = ParticipantRole.all().filter('particiant = ', participant)
                db.delete(pRoles)
            db.delete(participants)
            
            roles = Role.all().filter('project = ', project)
            db.delete(roles)
            
            tasks = Task.all().filter('project = ', project)
            db.delete(tasks)
            
            db.delete(project)
            self.redirect('/projects')
        else:
            self.redirect('/editProjectForm?projectId=%s' % (str(project.key())))
        
application = webapp.WSGIApplication([
  ('/', Login), 
  ('/Logout', Logout), 
  ('/projects', ListProject), 
  ('/createProject', CreateProject), 
  ('/createNewProject', CreateNewProject), 
  ('/editProjectForm', EditProjectForm), 
  ('/editProject', EditProject),
  ('/deleteProject', DeleteProject), 
  ('/roles', role.ListRoles), 
  ('/createRoleForm', role.CreateRoleForm), 
  ('/createRole', role.CreateRole), 
  ('/deleteRole', role.DeleteRole), 
  ('/editRoleForm', role.EditRoleForm), 
  ('/saveRole', role.SaveRole), 
  ('/participants', user.ListParticipants), 
  ('/createParticipant', user.CreateParticipant), 
  ('/createParticipantAction', user.CreateParticipantAction), 
  ('/editParticipant', user.EditParticipant),
  ('/saveParticipant', user.SaveParticipant),
  ('/deleteParticipant', user.DeleteParticipant),
  ('/tasks', task.ListTasks),
  ('/createTask', task.CreateTask), 
  ('/createTaskAction', task.CreateTaskAction) , 
  ('/editTask', task.EditTask), 
  ('/saveTask', task.SaveTask), 
  ('/deleteTask', task.DeleteTask), 
  ('/saveComment', Comment.SaveComment)
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()    